package com.algorithm;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 项目名称: java_algorithm
 * @ClassName ShuZuZhongChuXianCiShuChaoGuoYiBanDeShuZiLcof
 * @Description 数组中出现次数超过一半的数字
 * @Author huipanxing huipanxing@chinasofti.com   @Date 2021/10/18 14:36
 */
public class ShuZuZhongChuXianCiShuChaoGuoYiBanDeShuZiLcof {
    public static void main(String[] args) {
        int [] nums={1, 2, 3, 2, 2, 2, 5, 4, 2};
        System.out.println(majorityElement(nums));
    }

    public static int majorityElement(int[] nums) {
        Map<Integer,Integer> map=new HashMap<>();
        for (int num : nums) {
            if (map.keySet().contains(num)){
                map.put(num,map.get(num)+1);
            } else {
                map.put(num,0);
            }
        }
        Optional<Map.Entry<Integer, Integer>> max = map.entrySet().stream().max(Map.Entry.comparingByValue());
        Integer integer = max.map(x -> x.getKey()).orElse(0);
        return integer;
    }
}
